const Controller = require('egg').Controller 

class Comment extends Controller {
    
    async index() {
        const { ctx } = this
        const list = ctx.service.comment.list();
        ctx.body = list;
    }

    async get() {
        const { ctx } = this

        try {
            const res = await ctx.model.Comment.find()
            if (res.length!==0) {
                ctx.body = {
                    code:200,
                    msg:'成功',
                    data:res,
                }
            } else {
                ctx.body = {
                    code:404,
                    msg:'无数据',
                    data:[],
                }
            }
        } catch(e) {
            ctx.body = {
                code: 500,
                msg:e,
            }
        }
    }

    async add() {
        const { ctx } = this
        const { content } = ctx.query
        if (!content) {
            ctx.body = {
                code: 500,
                msg: '未指定评论的内容!'
            }
            return 
        }
        try {
            const newComment = new ctx.model.Comment({
                content:content,
            })
            const res = await newComment.save()
            if (res.id != null) {
                ctx.body = {
                    code:200,
                    msg:'成功',
                    data:res,
                }
            } else {
                ctx.body = {
                    code: 500,
                    msg: '创建失败，服务器异常,请稍后！'
                }
            }

        } catch(e) {
            ctx.body = {
                code:500,
                msg:'网络链接错误!',
            }
        }
    }

    async post() {
        const { ctx } = this
        const { content } = ctx.request.body
        if (!content) {
            ctx.body = {
                code: 500,
                msg: '未指定评论的内容!'
            }
            return 
        }
        try {
            const newComment = new ctx.model.Comment({
                content:content,
            })
            const res = await newComment.save()
            if (res.id != null) {
                ctx.body = {
                    code:200,
                    msg:'成功',
                    data:res,
                }
            } else {
                ctx.body = {
                    code: 500,
                    msg: '创建失败，服务器异常,请稍后！'
                }
            }

        } catch(e) {
            ctx.body = {
                code:500,
                msg:'网络链接错误!',
            }
        }
    }

}

module.exports = Comment